import {Component, OnInit, Input, Output, EventEmitter, TemplateRef} from '@angular/core';
import {ActivatedRoute, Route} from '@angular/router';
import {BsModalRef} from "ngx-bootstrap/modal/bs-modal-ref.service";
import {BsModalService} from "ngx-bootstrap/modal";

import { NormalService } from "../../apiServices/normal.service"
import { User } from "../../apiServices/user"
import {RequestClientService} from '../../apiServices/request-client.service';

@Component({
    selector: 'login',
    templateUrl: './login.template.html',
    styleUrls: ['/dialog.style.scss']
})
export class LoginComponent implements OnInit{
    public language: string = 'en';
    @Input()
    set showDialog(showDialog: boolean) {
        this._showDialog = showDialog;
        if(this._showDialog === true){
            this.getCaptchaImg();
        }
    }
    @Output() toggleLoginDialogEvent = new EventEmitter();
    _showDialog: boolean = false;
    public showLogin: boolean = true;
    public tipShowed: boolean = false;
    public createModel: User = new User();
    public logModel: any;
    verifyValid: boolean = false;
    getVerifyError: boolean = false;
    getCodeBtnName: string = 'Get Code';
    canGetVerifyCode: boolean = true;
    modalRef: BsModalRef;

    captchaImg: any = null;
    captchaCode: string = null;
    captchaValid: boolean = false;
    isChecked = false;
    isSignup: any = {en: 'success!', zh: '注册成功!'};

    captchaId: string;

    canGetEmail: boolean = true;
    getEmailName: string = 'submit';
    sendEmailError: boolean = false;

    constructor(
        private request: RequestClientService,
        private normalService: NormalService,
        private modalService: BsModalService,
    ) {
        // this.language = normalService.lang;
        this.language = request.language;

        if(this.language == 'en'){
            this.getCodeBtnName = 'Get Code';
        }
        if(this.language == 'zh'){
            this.getCodeBtnName = '发送';
        }
        if(this.language == 'en'){
            this.getEmailName = 'submit';
        }else if(this.language == 'zh'){
            this.getEmailName = '提交';
        }
    }
 
    openModal(template: TemplateRef<any>) {
        this.modalRef = this.modalService.show(template);
    }
    toggleDialog(): void {
        this._showDialog = !this._showDialog;
        this.toggleLoginDialogEvent.emit(1);
    }
    toggleLogin(): void {
        this.showLogin = !this.showLogin;
    }
    showTips(tip): void {
        if(tip == 'register') this.tipShowed = !this.tipShowed;
    }
    login(): void {
        this.normalService.login(this.createModel, this.captchaCode).then((result) => {
            this.getCaptchaImg();
        }).catch((error) => {
            this.getCaptchaImg();
            if(error.code != 499){
                if(this.normalService.lang == 'en'){
                    this.showMessage("Your email or password is wrong, please try again later ");
                }
                if(this.normalService.lang == 'zh'){
                    this.showMessage("您的邮箱或密码输入有误，请重试");
                }
            }else if(error.code == 499){
                this.showMessage(this.normalService.getErrors(error));
            }
           // this.showMessage(this.normalService.getErrors(error));
        });
    }
    signUp(): void {
        this.normalService.signUp(this.createModel).then((result) => {
            if(this.normalService.lang == 'en')
                this.showMessage(this.isSignup.en);
            if(this.normalService.lang == 'zh')
                this.showMessage(this.isSignup.zh);
            this.showLogin = true;
        }).catch((error) => {
            this.showMessage(error.message);
        });
    }
    forgetPass(email: string) {
        this.canGetEmail = false;
        if(this.normalService.lang == 'en'){
            this.getEmailName = 'sending...';
        }else if(this.normalService.lang == 'zh'){
            this.getEmailName = '发送中...';
        }
        this.normalService.forgetPassword(email, this.language).then((result) => {
            if(result && result.code && result.code ===200){
                this.showMessage(this.normalService.getSucc(result.message));
                this.sendEmailError = false;
                this.canGetEmail = false;
                let count = 120;
                this.getEmailName = count.toString();
                let id = setInterval(() => {
                    --count;
                    if(count === 0){
                        clearInterval(id);
                        if(this.normalService.lang == 'en'){
                            this.getEmailName = 'submit';
                        }else if(this.normalService.lang == 'zh'){
                            this.getEmailName = '提交';
                        }
                        this.canGetEmail = true;
                    }else{
                        this.getEmailName = count.toString();
                    }
                },1000);
            }else{
                this.sendEmailError = false;
                this.canGetEmail = true;
                if(this.normalService.lang == 'en'){
                    this.getEmailName = 'submit';
                }else if(this.normalService.lang == 'zh'){
                    this.getEmailName = '提交';
                }
            }

        }).catch((error) => {
            this.sendEmailError = false;
            this.canGetEmail = true;
            if(this.normalService.lang == 'en'){
                this.getEmailName = 'submit';
            }else if(this.normalService.lang == 'zh'){
                this.getEmailName = '提交';
            }
            this.showMessage(this.normalService.getErrors(error));
        });
    }
    getVerify() {
        this.canGetVerifyCode = false;
        if(this.language == 'en'){
            this.getCodeBtnName = 'getting...';
        }
        if(this.language == 'zh'){
            this.getCodeBtnName = '发送中...';
        }
        
        this.normalService.getVerify(this.createModel.email).then((result) => {
            if (result && result.code && result.code === 200) {
                this.getVerifyError = false;
                this.canGetVerifyCode = false;
                let count = 180;
                this.getCodeBtnName = count.toString();
                let id = setInterval(() => {
                    --count;
                    if (count === 0) {
                        clearInterval(id);
                        if(this.language == 'en'){
                            this.getCodeBtnName = 'Get Code';
                        }
                        if(this.language == 'zh'){
                            this.getCodeBtnName = '发送';
                        }
                        this.canGetVerifyCode = true;
                    } else {
                        this.getCodeBtnName = count.toString();
                    }
                }, 1000);
            } else {
                this.getVerifyError = true;
                this.canGetVerifyCode = true;
                if(this.language == 'en'){
                    this.getCodeBtnName = 'Get Code';
                }
                if(this.language == 'zh'){
                    this.getCodeBtnName = '发送';
                }
            }
        }).catch((error) => {
            this.getVerifyError = true;
            this.canGetVerifyCode = true;
            if(this.language == 'en'){
                this.getCodeBtnName = 'Get Code';
            }
            if(this.language == 'zh'){
                this.getCodeBtnName = '发送';
            }
            this.showMessage(this.normalService.getErrors(error));
        });
    }
    checkVerify() {
        console.log(this.createModel.email, this.createModel.code);
        this.normalService.checkVerify(this.createModel.email, this.createModel.code).then((result) => {
            if (result && result.success && result.success === true) {
                this.verifyValid = true;
            } else {
                this.verifyValid = false;
            }
        }).catch((error) => {
            this.verifyValid = false;
            // this.showMessage(this.normalService.getErrors(error));
        });
    }

    checkCaptcha() {
        this.normalService.checkCaptcha(this.captchaId, this.captchaCode).then(result => {
            let resultObj = JSON.parse(result);
            this.captchaValid = (resultObj.code === 0);
        }).catch(error => {
            this.captchaValid = false;
        });
    }

    getCaptchaImg() {
        this.normalService.getCaptchaImg({
            width: 150,
            height: 45,
            length: 4,
            mode: 0,
            howHollowLine: true,
            noiseDot: true,
        }).then(result => {
            let resultImg = JSON.parse(result);
            if (resultImg.code === 0) {
                this.captchaId = resultImg.captchaId;
                document.getElementById('captchaImg').setAttribute('src', resultImg.data);
                this.checkCaptcha();
            }
        }).catch(error => {
            this.showMessage(error);
        });
    }

    showMessage(message: string) {
        alert(message);
    }

    isCheck(){
        this.isChecked = !this.isChecked;
    }

    ngOnInit(): void {
        this.getCaptchaImg();
    }
}
